<?php
/**
 * 签到记录模型
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\common\model;

class CheckinRecord extends ModelBase
{

    
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    
    // 时间字段
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 字段类型转换
    protected $type = [
        'id' => 'integer',
        'user_id' => 'integer',
        'points' => 'integer',
        'continuous_days' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
    ];
    
    /**
     * 获取创建时间格式化
     */
    public function getCreateTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }
    
    /**
     * 获取更新时间格式化
     */
    public function getUpdateTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '';
    }
    
    /**
     * 获取用户签到记录
     */
    public function getUserCheckinRecords($userId, $startDate = null, $endDate = null, $paginate = false)
    {
        $where = ['user_id' => $userId];
        
        if ($startDate) {
            $where['checkin_date'] = ['>=', $startDate];
        }
        
        if ($endDate) {
            if (isset($where['checkin_date'])) {
                $where['checkin_date'] = ['between', [$startDate, $endDate]];
            } else {
                $where['checkin_date'] = ['<=', $endDate];
            }
        }
        
        return $this->getList($where, true, 'checkin_date desc', $paginate);
    }
    
    /**
     * 获取用户今日签到记录
     */
    public function getTodayCheckin($userId)
    {
        $today = date('Y-m-d');
        return $this->getInfo(['user_id' => $userId, 'checkin_date' => $today]);
    }
    
    /**
     * 获取用户连续签到天数
     */
    public function getContinuousCheckinDays($userId)
    {
        $continuousDays = 0;
        
        for ($i = 0; $i < 365; $i++) {
            $checkDate = date('Y-m-d', strtotime("-{$i} day"));
            $checkin = $this->getInfo([
                'user_id' => $userId,
                'checkin_date' => $checkDate
            ]);
            
            if ($checkin) {
                $continuousDays++;
            } else {
                break;
            }
        }
        
        return $continuousDays;
    }
    
    /**
     * 获取用户本月签到记录
     */
    public function getMonthCheckinRecords($userId, $year = null, $month = null)
    {
        if (!$year) {
            $year = date('Y');
        }
        if (!$month) {
            $month = date('m');
        }
        
        $monthStart = "{$year}-{$month}-01";
        $monthEnd = date('Y-m-t', strtotime($monthStart));
        
        return $this->getUserCheckinRecords($userId, $monthStart, $monthEnd);
    }
    
    /**
     * 获取签到统计
     */
    public function getCheckinStatistics($userId = null, $startTime = null, $endTime = null)
    {
        $where = [];
        
        if ($userId) {
            $where['user_id'] = $userId;
        }
        
        if ($startTime) {
            $where['create_time'] = ['>=', $startTime];
        }
        
        if ($endTime) {
            if (isset($where['create_time'])) {
                $where['create_time'] = ['between', [$startTime, $endTime]];
            } else {
                $where['create_time'] = ['<=', $endTime];
            }
        }
        
        $totalCount = $this->stat($where, 'count');
        $totalPoints = $this->getValue($where, 'SUM(points)') ?: 0;
        $avgPoints = $totalCount > 0 ? round($totalPoints / $totalCount, 2) : 0;
        
        return [
            'total_count' => $totalCount,
            'total_points' => $totalPoints,
            'avg_points' => $avgPoints
        ];
    }
    
    /**
     * 获取签到排行榜
     */
    public function getCheckinRanking($limit = 10, $type = 'continuous')
    {
        if ($type == 'continuous') {
            // 连续签到排行榜
            $sql = "SELECT user_id, MAX(continuous_days) as max_continuous_days 
                    FROM {$this->getTable()} 
                    GROUP BY user_id 
                    ORDER BY max_continuous_days DESC 
                    LIMIT {$limit}";
        } else {
            // 总签到次数排行榜
            $sql = "SELECT user_id, COUNT(*) as total_checkins, SUM(points) as total_points 
                    FROM {$this->getTable()} 
                    GROUP BY user_id 
                    ORDER BY total_checkins DESC 
                    LIMIT {$limit}";
        }
        
        return \think\facade\Db::query($sql);
    }
    
    /**
     * 清理过期签到记录
     */
    public function cleanExpiredRecords($days = 365)
    {
        $expireDate = date('Y-m-d', strtotime("-{$days} day"));
        $where = ['checkin_date' => ['<', $expireDate]];
        
        return $this->deleteInfo($where);
    }
    
    /**
     * 检查用户是否已签到
     */
    public function isCheckedIn($userId, $date = null)
    {
        if (!$date) {
            $date = date('Y-m-d');
        }
        
        $checkin = $this->getInfo(['user_id' => $userId, 'checkin_date' => $date]);
        return !empty($checkin);
    }
    
    /**
     * 获取用户最后签到记录
     */
    public function getLastCheckin($userId)
    {
        return $this->getInfo(['user_id' => $userId], true, 'checkin_date desc');
    }
}